package com.cx.exception;

import com.cx.util.ResultUtil;
import com.cx.util.WebUtil;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.http.HttpStatus;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;


// 认证失败的异常处理器
@Component
public class AuthenticationEntryPointImpl implements AuthenticationEntryPoint {
    private static final ObjectMapper MAPPER = new ObjectMapper();
    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException, ServletException {

        ResultUtil result = new ResultUtil(HttpStatus.UNAUTHORIZED.value(), "用户认证失败请重新登录！", null);
        String json = MAPPER.writeValueAsString(result);
        // 处理异常
        WebUtil.renderString(response,json);
    }
}
